package ru.maksb.exchange.domain;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import ru.maksb.exchange.service.BuyOrdersComparator;
import ru.maksb.exchange.service.SellOrdersComparator;

public class OpenBook {
    /*
     * Stores book info for one ticket
     */
    private String ticket;
    private SortedSet<Order> sellOrders = new TreeSet<Order>(new SellOrdersComparator());
    private SortedSet<Order> buyOrders = new TreeSet<Order>(new BuyOrdersComparator());
    private double defaultSellPrice;
    private double defaultBuyPrice;

    public OpenBook(String ticket, double defaultbuyprice,
            double defaultcellprice) {
        this.ticket = ticket;
        this.defaultBuyPrice = defaultbuyprice;
        this.defaultSellPrice = defaultcellprice;
    }

    public String getTicket() {
        return ticket;
    }

    public SortedSet<Order> getSellOrders() {
        return Collections.unmodifiableSortedSet(sellOrders);
    }

    public SortedSet<Order> getBuyOrders() {
        return Collections.unmodifiableSortedSet(buyOrders);
    }

    public double getDefaultSellPrice() {
        return defaultSellPrice;
    }

    public double getDefaultBuyPrice() {
        return defaultBuyPrice;
    }

    public void add(Order order) {
        if (!ticket.equals(order.getTicket())) {
            throw new IllegalArgumentException("Order and book tickets must be equal:" 
                            + ticket + " and " + order.getTicket());
        }
        if (OrderSide.BUY.equals(order.getSide())) {
            buyOrders.add(order);
            return;
        }
        if (OrderSide.SELL.equals(order.getSide())) {
            sellOrders.add(order);
            return;
        }
        throw new IllegalArgumentException("Order must be of BUY or SELL side");
    }

    public boolean remove(Order order) {
        switch (order.getSide()) {
        case BUY:
            return buyOrders.remove(order);
        case SELL:
            return sellOrders.remove(order);
        default:
            return false;
        }
    }
}
